package com.rfid.assistant.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rfid.assistant.QrScanActivity;
import com.rfid.assistant.R;
import com.rfid.assistant.activity.adapter.WlanDeviceAdapter;
import com.rfid.event.SendStatus;
import com.rfid.sockethelper.ClientManager;
import com.rfid.sockethelper.ClientSocketHelper;
import com.rfid.sockethelper.IOHelper;
import com.rfid.sockethelper.SocketBase;
import com.rfid.wlandirectlib.WifiDirectManager;
import com.rfid.wlandirectlib.WifiP2PListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Collection;

import butterknife.BindView;
import butterknife.ButterKnife;

public class WlanAcitivty extends AppCompatActivity implements WifiP2PListener, WlanDeviceAdapter.OnItemClickListener,SocketBase.OnReceiveListener {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.device)
    TextView mDeviceText;
    WlanDeviceAdapter mWlanDeviceAdapter;
    private String mHost;
    private ProgressDialog mProgressDialog;
    private boolean isSend;

    public static void startActivity(Context context,boolean send) {
        Intent intent = new Intent();
        intent.putExtra("send",send);
        intent.setClass(context,WlanAcitivty.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wlan_layout);
        ButterKnife.bind(this);
        isSend = getIntent().getBooleanExtra("send",false);
        mWlanDeviceAdapter = new WlanDeviceAdapter();
        mWlanDeviceAdapter.setOnItemClickListener(this);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        mRecyclerView.setAdapter(mWlanDeviceAdapter);
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                100);
        int ret = WifiDirectManager.getInstance().initP2p(this);
        if (ret != 0) {
            Toast.makeText(this, "wifi直连初始化失败：" + ret, Toast.LENGTH_SHORT);
        }
        System.out.println("init wlan p2p ret = " + ret);
        WifiDirectManager.getInstance().startDiscovery();
        mDeviceText.setText("正在扫描");
    }


    private void showProgress() {
        if (mProgressDialog != null) {
            mProgressDialog.show();
            return;
        }
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("正在建立数据通道");
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.wlan_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.wlan) {
            WifiDirectManager.getInstance().startDiscovery();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onWifiP2pEnabled(boolean isEnabled) {
    }

    @Override
    public void onDiscoverPeers(boolean isSuccess) {
    }

    @Override
    public void onSelfDeviceAvailable(@NonNull WifiP2pDevice wifiP2pDevice) {
        mDeviceText.setText("我的设备：" + wifiP2pDevice.deviceName);
    }

    @Override
    public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
        if (wifiP2pInfo != null) {
            System.out.println("wifiP2pInfo = " + wifiP2pInfo);
            if (wifiP2pInfo.groupOwnerAddress != null && !wifiP2pInfo.isGroupOwner) {
                Toast.makeText(this, "通道建立：" + wifiP2pInfo.groupOwnerAddress, Toast.LENGTH_SHORT).show();
                String host = wifiP2pInfo.groupOwnerAddress.getHostAddress();
                ClientSocketHelper helper = ClientManager.getManager().getClient(host);
                if (helper ==null ) {
                    mHost = host;
                    ClientManager.getManager().postConnect(host);
                    showProgress();
                } else if (helper.isConnecting()) {
                } else if (!helper.isConnect()) {
                    mHost = host;
                    ClientManager.getManager().postConnect(host);
                    showProgress();
                } else {
                    //connected,nothing to do
                }
            }
        } else {
            Toast.makeText(this,"通道断开！",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPeersAvailable(@NonNull Collection<WifiP2pDevice> wifiP2pDeviceList) {
        mWlanDeviceAdapter.setWifiP2pDeviceList(wifiP2pDeviceList);
    }

    @Override
    public void onDiscoveryStatusChange(boolean isScan) {
//        Toast.makeText(this,isScan?"开始扫描":"停止扫描",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onItemClick(WifiP2pDevice wifiP2pDevice) {
        //已建立直连未建立tcp连接
        if (wifiP2pDevice.status == WifiP2pDevice.CONNECTED && mHost == null) {
            return;
        }
        //重新建立tcp连接
        if (wifiP2pDevice.status == WifiP2pDevice.CONNECTED) {
            ClientManager.getManager().clear(mHost);
            ClientManager.getManager().postConnect(mHost);
            showProgress();
            return;
        }
        WifiDirectManager.getInstance().cancelConnect();
        ClientManager.getManager().clear(mHost);
        WifiDirectManager.getInstance().removeGroup();
        mDeviceText.postDelayed(new Runnable() {
            @Override
            public void run() {
                WifiDirectManager.getInstance().connect(wifiP2pDevice);
            }
        },500);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ClientManager.getManager().destroy();
        WifiDirectManager.getInstance().cancelConnect();
        WifiDirectManager.getInstance().setListener(null);
        WifiDirectManager.getInstance().removeGroup();
        WifiDirectManager.getInstance().destroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        WifiDirectManager.getInstance().setListener(this);
        ClientManager.getManager().addListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
        WifiDirectManager.getInstance().setListener(null);
        ClientManager.getManager().removeListener(this);
    }


    @Override
    public void onReceived(String ip, short cmd, CharSequence... text) {
        System.out.println("text = " + text[0]);
    }

    @Override
    public void onConnect(String ip, boolean connect) {
        Toast.makeText(this,"连接：" + connect + ":" + ip,Toast.LENGTH_SHORT).show();
        mDeviceText.setText("连接建立" + (connect?"成功:":"失败:") + ip);
        if (connect) {
            Intent intent = getIntent();
            String action = intent.getAction();
            Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
            if (uri == null) {
                uri = intent.getData();
            }
            if (uri != null || isSend) {
                SendActivity.startActivity(this,uri,ip);
                return;
            }
            SafeDoorConfigActivity.startActivity(this,mHost);
        }
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

}
